import { createAction, handleActions } from 'redux-actions'
import { CALL_API } from 'redux-api-middleware'

import getApiPath from '../../helpers/getApiPath'
import getFetchOptions from '../../helpers/getFetchOptions'
import getQuery from '../../helpers/getQuery'

// ------------------------------------
// Constants (Action Types)
// ------------------------------------

// pending request
const FETCH_REQUEST = Symbol('FETCH_REQUEST')
const FETCH_FAILURE = Symbol('FETCH_FAILURE')


// ------------------------------------
// Actions (Action Creator)
// ------------------------------------


export const login = (params, callback) => {

  const fetchOptions = getFetchOptions(getApiPath('Passport/WarehouseLogin', params), 'POST', {
    body: null
  })

  return {
    [CALL_API]: {
      ...fetchOptions,
      complete: callback,
      types: [
        FETCH_REQUEST,
        {
          type: Symbol('LOGIN_SUCCESS'),
          payload: (action, state, json) => json.data
        },
        FETCH_FAILURE
      ]
    }
  }
}

export const getAppid = (callback) => {
  const fetchOptions = getFetchOptions(getApiPath('DataSource/GetConfigByCode?code=SZWLKJ_WXSERVICE_APPID'))

  return {
    [CALL_API]: {
      ...fetchOptions,
      complete: callback,
      types: [
        FETCH_REQUEST,
        {
          type: Symbol('GET_APPID_SUCCESS'),
          payload: (action, state, json) => json.Data
        },
        FETCH_FAILURE
      ]
    }
  }
}


/**
 * 暴露actions到外面，方便使用react-redux connect绑定到Container Component
 */
export const actions = {
  login, // 保存
  getAppid
}

// ------------------------------------
// Reducers
// ------------------------------------
const initialState = {
  pending: false
}

export default handleActions({
  // 登录/登出pending
  [FETCH_REQUEST](state) {
    return {
      ...state,
      pending: true
    }
  },

  [FETCH_FAILURE](state) {
    return {
      ...state,
      pending: false
    }
  }

}, initialState)
